/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uia.is202.survey;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author n_aud5
 */
public class Result extends HttpServlet {

    @PersistenceUnit
    protected EntityManagerFactory emf;


    /**
     * Handle get requests by calling processRequest()
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        processRequest(req, resp);
    }


    /**
     * Handle post requests by calling processRequest()
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        processRequest(req, resp);
    }


    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("select r from Response r");
        List<Response> responses = q.getResultList();


        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>Survey</title></head><body>");
        out.println("<h1>Survey Results</h1>");
        out.println("<p>We got "+responses.size()+" responses</p>");

        out.println("<table>");
        out.println("<tr><th>Alder</th><th>Postnr</th></tr>");
        for (Response r : responses) {
            out.println("<tr><td>"+r.getAlder()
                    +"</td><td>"+r.getPostnr()+"</td></tr>");
        }
        out.println("</table>");

        out.println("</body></html>");

    }


}
